/*
 *  Copyright 2008-2010 www.jrails.org
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.rails.core.db;

import java.lang.reflect.Method;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import org.apache.log4j.Logger;

/**
 * 获取./config/db.properties 所配置的数据源。
 * @author jack
 *
 */
public final class DSConfig {

	private final Logger logger = Logger.getLogger(this.getClass());	
	private final static String DRIVER_METHOD = "setDriverClassName";
	private final static String URL_METHOD = "setUrl";
	private final static String USERNAME_METHOD = "setUsername";
	private final static String PASSWORD_METHOD = "setPassword";

	private DataSource dataSource;
	
	public DSConfig(String jndi) {
		super();
		try {
			dataSource = (DataSource) new InitialContext().lookup(jndi);
		} catch (NamingException e) {
			logger.error(e.getMessage(),e);
		}
	}

	@SuppressWarnings("unchecked")
	public DSConfig(String ds, String driver, String url,
			String username, String password) throws Exception {
		super();		
		try {
			final Class<DataSource> c = (Class<DataSource>) Class.forName(ds);
			dataSource = c.newInstance();
			Method mtd = c.getDeclaredMethod(DRIVER_METHOD, String.class);
			mtd.invoke(dataSource, driver);
			mtd = c.getDeclaredMethod(URL_METHOD, String.class);
			mtd.invoke(dataSource, url);
			mtd = c.getDeclaredMethod(USERNAME_METHOD, String.class);
			mtd.invoke(dataSource, username);
			mtd = c.getDeclaredMethod(PASSWORD_METHOD, String.class);
			mtd.invoke(dataSource, password);
		} catch (Exception e) {
			throw e;
		}
	}
	
	public DataSource getDataSource(){
		return dataSource;
	}

}
